package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heima.behavior.config.CacheService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.constants.message.HotArticleConstants;
import com.heima.common.constants.user.UserRelationConstants;
import com.heima.model.app.UpdateArticleMess;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Autowired
    private CacheService cacheService;
    @Autowired
    KafkaTemplate kafkaTemplate;
    /**
     * 阅读行为
     *
     * @param readBehaviorDto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto readBehaviorDto) {
        //1.参数校验
        if (readBehaviorDto == null || readBehaviorDto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.用户是否登录
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.更新阅读次数

        String hGet = (String) cacheService.hGet(UserRelationConstants.BEHAVIOR_READ + apUser.getId(), readBehaviorDto.getArticleId().toString());
        if (StringUtils.isNotBlank(hGet)){
            ReadBehaviorDto dto = JSON.parseObject(hGet, ReadBehaviorDto.class);
            readBehaviorDto.setCount(dto.getCount()+1);
            log.info("更新阅读次数");
        }
        //4.记录阅读行为
    
        cacheService.hPut(UserRelationConstants.BEHAVIOR_READ+apUser.getId(),readBehaviorDto.getArticleId().toString(), JSON.toJSONString(readBehaviorDto));
        log.info("记录阅读次数成功");
        //实时计算文章分值
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        mess.setArticleId(readBehaviorDto.getArticleId());
        kafkaTemplate.send(HotArticleConstants.HOTARTICLE_SCORE_INPUT_TOPIC, JSON.toJSONString(mess));
        log.info("*****kafkaTemplate send read");
        //5.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
